<script lang="ts" setup>
import { getOSSURL } from "@/utils/utils";
import QuestionOption from "./question-option.vue";
import { Loading } from "@nutui/icons-vue";
import {
  PracticeMode,
  QuestionState,
  QuestionOptionIndex,
  UpdateActionRecordParams,
  QuestionOptionNo,
  QuestionType,
  Question,
} from "@/types/practice";
import { useCourseStore } from "@/store/modules/course";
import { showToast } from "@nutui/nutui";
import "@nutui/nutui/dist/packages/toast/style";

const props = defineProps<{
  mode: PracticeMode;
  currentIndex: number;
  questionState: QuestionState;
  choosedAnswer?: QuestionOptionIndex[];
}>();

const courseStore = useCourseStore();

const emit = defineEmits<{
  (e: "correct"): void;
  (e: "previewImg", imgUrl: string): void;
  (e: "feedback", questionId: Question["id"]): void;
  (e: "chooseAnswer", optionIndexList: QuestionOptionIndex[], isCorrect: boolean): void;
  (e: "updateActionRecord", params: UpdateActionRecordParams): void;
}>();

const question = computed(() => props.questionState.question);
const actionRecord = computed(() => props.questionState.actionRecord);

const questionTypeMap = {
  [QuestionType.JUDGE]: "判断题",
  [QuestionType.SINGLE]: "单选题",
  [QuestionType.MULTIPE]: "多选题",
};

const questionType = computed(() => questionTypeMap[question.value?.questionType || 1]);

const questionOptionMap: Record<QuestionOptionIndex, QuestionOptionNo> = {
  1: "A",
  2: "B",
  3: "C",
  4: "D",
};

const answerOptionsStr = computed(() => question.value?.questionOptionIndex.map((index) => questionOptionMap[index]).join(""));

const answerVisible = computed(() => {
  return props.mode === "view" || props.choosedAnswer?.length;
});

// 已选择的答案（临时
let chooseAnswer = ref<QuestionOptionIndex[]>([]);
watch(
  () => props.currentIndex,
  () => {
    chooseAnswer.value = [];
  }
);

// 提交答案
const submitAnswer = () => {
  if (question.value?.questionType === QuestionType.MULTIPE) {
    if (chooseAnswer.value.length < 2) {
      showToast.fail("请选择两个及以上的答案", {
        bgColor: "#999",
      });
      return;
    }
  }
  const isCorrect = chooseAnswer.value.sort().join("") === question.value?.questionOptionIndex.sort().join("");
  emit("chooseAnswer", chooseAnswer.value, isCorrect);
  emit("updateActionRecord", {
    questionId: question.value!.id,
    isCorrect: isCorrect,
  });
  chooseAnswer.value = [];

  // 正确的话，通知父元素滑动到下一题
  isCorrect && emit("correct");
};

// 提交按钮是否可见
const submitAnswerBtnVisible = computed(() => !answerVisible.value && question.value?.questionType === QuestionType.MULTIPE);

// 已选择的答案的文本展示
const choosedOptionsStr = computed(() => props.choosedAnswer?.map((index) => questionOptionMap[index]).join(""));

// 选项状态
const optionsState = computed(() => {
  return question.value?.questionAnswer.map((option) => {
    // 背题模式
    if (answerVisible.value)
      if (question.value?.questionOptionIndex.includes(option.index))
        // 正确的
        return "correct";
      // 错误的
      else if (props.mode !== "view" && props.choosedAnswer?.includes(option.index)) return "wrong";

    if (chooseAnswer.value.includes(option.index)) return "choosed";

    return "empty";
  });
});

// 选择答案
const selectOption = (index: QuestionOptionIndex) => {
  if (answerVisible.value) return;

  if (question.value?.questionType === QuestionType.JUDGE || question.value?.questionType === QuestionType.SINGLE) {
    // 单选题或者判断题
    chooseAnswer.value = [index];
    submitAnswer();
  } else if (question.value?.questionType === QuestionType.MULTIPE) {
    // 多选题
    if (chooseAnswer.value.includes(index))
      // 已经选择了，取消选择
      chooseAnswer.value = chooseAnswer.value.filter((item) => item !== index);
    // 未选择，选择
    else chooseAnswer.value.push(index);

    chooseAnswer.value = chooseAnswer.value.sort();
  }
};
</script>

<template>
  <div class="min-w-full h-full of-auto">
    <template v-if="question">
      <div class="p-3">
        <!-- 题目 -->
        <div>
          <span class="inline-block mr-2 v-middle px-1.5 py-1 rd-1 bg-blue-4 c-white text-xs">{{ questionType }}</span>
          <span class="v-middle">{{ question.questionTitle }}</span>
        </div>

        <!-- 题目配图 -->
        <nut-image
          v-if="question.questionPic"
          class="h-40 mx-auto my-3"
          :src="getOSSURL(question.questionPic)"
          fit="contain"
          show-loading
          @click="emit('previewImg', getOSSURL(question.questionPic))"
        >
          <template #loading>
            <Loading width="16px" height="16px" name="loading" />
          </template>
        </nut-image>

        <!-- 选项 -->
        <div class="mt-4 flex flex-col gap-3">
          <QuestionOption
            v-for="item in question.questionAnswer"
            :key="item.index"
            :text="item.answer"
            :option="questionOptionMap[item.index]"
            :state="optionsState?.[item.index - 1]"
            @click="selectOption(item.index)"
          />
        </div>

        <!-- 提交按钮 -->
        <div v-if="submitAnswerBtnVisible" class="mt-4">
          <nut-button class="w-full" block type="primary" @click="submitAnswer">确认答案</nut-button>
        </div>

        <!-- 答案 -->
        <div v-if="answerVisible" class="mt-4 px-4 py-2 bg-white rd-3">
          答案：<span class="inline-block mr-5 c-emerald-5">{{ answerOptionsStr }}</span>
          <template v-if="mode === 'exam'"
            >您选择：<span class="c-emerald-5">{{ choosedOptionsStr }}</span></template
          >
        </div>

        <!-- 解释 -->
        <div v-if="answerVisible" class="mt-4 px-4 py-3 bg-white rd-3">
          <div class="flex items-center justify-center gap-2">
            <span class="w-1.5 h-4 bg-blue-4"></span>
            <span class="text-lg">{{ courseStore.isVIP ? "技巧解析" : "官方解释" }}</span>
            <span class="w-1.5 h-4 bg-blue-4"></span>
          </div>

          <div class="mt-2">{{ courseStore.isVIP ? question.skillText || question.officialGuide : question.officialGuide }}</div>

          <div class="mt-2 text-sm c-gray-5">
            我做过
            <span class="c-red-5">{{ actionRecord?.actionCount }}</span>
            次，做错
            <span class="c-red-5">{{ actionRecord?.errorCount }}</span>
            次
          </div>
        </div>

        <!-- 问题反馈 -->
        <!-- <div class="mt-1 c-gray-4 text-sm text-right underline-solid" block type="primary" @click="emit('feedback', question.id)">问题反馈</div> -->
      </div>
    </template>
    <template v-else>
      <nut-empty description="来到了知识的荒漠~" />
    </template>
  </div>
</template>
